<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div>
            <el-input clearable placeholder="请输入内容" v-model="queryInfo.query" @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col class="addBtn" :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 添加用户的对话框 -->
      <el-row>
        <el-dialog @close="dialogClose" title="添加用户" :visible.sync="dialogVisible" width="30%">
          <!-- 内容主体部分 若需要验证格式 则应该有prop -->
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 按钮部分 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>

      <!-- 用户列表区域 -->
      <el-row class="middle">
        <template>
          <el-table stripe border :data="userList" style="width: 100%">
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="mobile" label="电话"></el-table-column>
            <el-table-column prop="role_name" label="角色"></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-tooltip effect="dark" content="修改" placement="top-start" :enterable="false">
                  <el-button type="primary" @click="showDialogUpdata(scope.row.id)" icon="el-icon-edit" circle></el-button>
                </el-tooltip>

                <!-- 删除按钮 -->
                <el-tooltip effect="dark" content="删除" placement="top-start" :enterable="false">
                  <el-button type="danger" @click="deleteUser(scope.row.id)" icon="el-icon-delete" circle></el-button>
                </el-tooltip>

                <!-- 分配角色 enterable	鼠标是否可进入到 tooltip 中 -->
                <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
                  <el-button @click="setRolesList(scope.row)" type="warning" icon="el-icon-setting" circle></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-row>

      <!-- 分页功能 -->
      <el-row>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[2, 3, 4, 5]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-row>

      <!-- 修改用户的对话框 -->
      <el-row>
        <el-dialog @close="editClose" title="修改用户" :visible.sync="dialogUpdata" width="30%">
          <!-- 内容主体部分 -->
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px" class="demo-ruleForm">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 按钮部分 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogUpdata = false">取 消</el-button>
            <el-button type="primary" @click="updateUser">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>

      <!-- 为用户分配角色的对话框 -->
      <el-row>
        <el-dialog title="分配角色" @close="rolesDialogClose" :visible.sync="setRolesDialogVisible" width="50%">
          <div class="roles">
            <!-- <p>当前的用户：{{userInfo}}</p> -->
            <p>当前的用户：{{ userInfo.username }}</p>
            <p>当前的角色：{{ userInfo.role_name }}</p>
            <p>
              分配新角色：
              <el-select v-model="selectRoleId" placeholder="请选择角色">
                <el-option v-for="value in rolesList" :label="value.roleName" :key="value.id" :value="value.id"></el-option>
              </el-select>
            </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRoles">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmial = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmial.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱地址'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号码'))
    }
    return {
      input: '',
      queryInfo: {
        query: '',
        pagenum: 1, //当前页码
        pagesize: 2 //每页显示条数
      },
      userList: [],
      total: 0,
      //添加用户对话框是否显示
      dialogVisible: false,
      //修改用户对话框是否显示
      dialogUpdata: false,
      //分配角色对话框是否显示
      setRolesDialogVisible: false,
      // 角色列表
      rolesList: [],
      //已经选中的角色id值
      selectRoleId: '',
      //需要被分配角色的用户信息
      userInfo: {},
      dialogDelete: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 4,
            max: 10,
            message: '长度在 4 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //查询到的用户信息
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: response } = await this.$axios.get('users', {
        params: this.queryInfo
      })
      if (response.meta.status !== 200) return this.$message.error('获取用户列表失败')
      //   console.log(data)
      this.userList = response.data.users
      this.total = response.data.total
    },
    //监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      //   console.log(`每页 ${newSize} 条`)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      //   console.log(`当前页: ${newPage}`)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听用户状态的修改并发送请求
    async changeState(userInfo) {
      const { data: response } = await this.$axios.put('users/' + userInfo.id + '/state/' + userInfo.mg_state)
      if (response.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('设置状态失败')
      }
      return this.$message.success(response.meta.msg)
      // console.log(data)
    },
    //监听添加用户对话框关闭的事件
    dialogClose() {
      this.$refs.addFormRef.resetFields()
      // console.log(this)
    },
    //监听编辑用户对话框关闭的事件
    editClose() {
      this.$refs.editFormRef.resetFields()
      // console.log(this)
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return
        const { data: response } = await this.$axios.post('/users', this.addForm)
        if (response.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.dialogVisible = false //隐藏对话框
        this.getUserList() //重新获取用户列表
      })
    },
    //显示修改用户对话框
    async showDialogUpdata(id) {
      this.dialogUpdata = true
      const { data: response } = await this.$axios.get('users/' + id)
      // console.log(response)
      if (response.meta.status !== 200) return this.$message.error('查询用户信息失败')
      this.$message.success('查询用户信息成功')
      this.editForm = response.data
    },
    //修改用户信息
    async updateUser() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return
        const { data: response } = await this.$axios.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        // console.log(response)
        if (response.meta.status !== 200) return this.$message.error('修改用户信息失败')

        // 隐藏对话框
        this.dialogUpdata = false
        this.getUserList()
        this.$message.success('修改用户信息成功')
      })
    },
    //删除用户信息
    async deleteUser(id) {
      await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: response } = await this.$axios.delete('users/' + id)
          if (response.meta.status !== 200) return this.$message.error('删除用户信息失败')
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //显示分配角色对话框
    async setRolesList(userInfo) {
      this.userInfo = userInfo
      const { data: response } = await this.$axios.get('roles')
      if (response.meta.status !== 200) return this.$message.error('获取角色列表失败')

      this.rolesList = response.data
      //   console.log(response.data)
      this.setRolesDialogVisible = true
      return this.$message.success(response.meta.msg)
    },
    //监听添加分配角色对话框关闭的事件
    rolesDialogClose() {
      this.selectRoleId = ''
      this.userInfo = ''
      // console.log(this)
    },
    // 点击按钮分配角色
    async addRoles() {
      // 如果用户没有选择角色 提示错误信息
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }

      const { data: response } = await this.$axios.put('users/' + this.userInfo.id + '/role', {
        rid: this.selectRoleId
      })
      if (response.meta.status !== 200) {
        return this.$message.error('创建角色失败')
      }
      //   console.log(response.data)
      this.setRolesDialogVisible = false
      this.getUserList()
      return this.$message.success(response.meta.msg)
    }
  }
}
</script>

<style lang="less" scoped>
.addBtn {
  float: right;
}
.middle {
  margin: 20px 0;
}
.roles p {
  margin: 15px;
}
.block {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
